package com.blog.wu.myblog.controller;

import com.blog.wu.myblog.base.BaseController;
import com.blog.wu.myblog.config.ApplicationConstants;
import com.blog.wu.myblog.entity.LoginLog;
import com.blog.wu.myblog.entity.Permission;
import com.blog.wu.myblog.entity.UserInfo;
import com.blog.wu.myblog.service.LoginLogService;
import com.blog.wu.myblog.service.PermissionService;
import com.blog.wu.myblog.service.UserInfoService;
import com.blog.wu.myblog.util.HttpUtils;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author wuyanshen
 * @Date 2018-09-25 上午12:36
 * @Discription 主页controller
 */
@Controller
@RequestMapping("back")
public class BackIndexController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private LoginLogService loginLogService;

    @Autowired
    private PermissionService permissionService;

    //    @RequiresPermissions("find")
    @RequestMapping("index")
    public String index(HttpSession session, Model model) {
        logger.info("开始加载index页面...");
        try {
            //查询登录记录
            UserInfo user = (UserInfo) session.getAttribute("userinfo");
            List<Permission> permissions = permissionService.findPermissions(user);
            LoginLog loginLog = new LoginLog();
            loginLog.setLoginAccount(user.getUserAccount());
            List<LoginLog> list = loginLogService.findList(loginLog);
            model.addAttribute("permissions", permissions);
            model.addAttribute("loginlist", list);

            return "back/index";
        } catch (Exception e) {
            logger.info("加载index页面出错 {}", e.getMessage());
        } finally {
            logger.info("加载index页面结束...");
        }

        return null;
    }

    @RequestMapping("menu")
    @ResponseBody
    public List<Permission> userMenu(HttpSession session, Model model) {
        UserInfo user = (UserInfo) session.getAttribute("userinfo");
        List<Permission> allPermissions = permissionService.findList(new Permission());
        List<Permission> userPermissions = permissionService.findPermissions(user);

        Set<String> perms = new HashSet<>();
        for (Permission p : userPermissions) {
            perms.add(p.getPermissionName());
        }

        List<Permission> menus = new ArrayList<>();
        for (Permission permission : allPermissions) {
            if (permission.isRootNode()) {
                continue;
            }

            if (permission.getType().equals("0")) {
                continue;
            }

            if (!hasPermission(perms,permission)) {
                continue;
            }
            menus.add(permission);
        }
        return menus;
    }

    private boolean hasPermission(Set<String> permissions, Permission resource) {
        if(StringUtils.isEmpty(resource.getPermissionName())) {
            return true;
        }
        for(String permission : permissions) {
            WildcardPermission p1 = new WildcardPermission(permission);
            WildcardPermission p2 = new WildcardPermission(resource.getPermissionName());
            if(p1.implies(p2) || p2.implies(p1)) {
                return true;
            }
        }
        return false;
    }


    @RequestMapping("main")
    public String main(Model model, HttpServletRequest request, HttpSession session) {

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        logger.info("开始加载main页面...");
        try {
            int sessionTime = request.getSession().getMaxInactiveInterval();

            logger.info("session有时长：" + sessionTime);

            String ip = HttpUtils.getIp(request);
            logger.info("登录者的ip:" + ip);
            int count = userInfoService.count(null);

            int onlineCount = ApplicationConstants.CURRENT_LOGIN_COUNT;
            int historyCount = ApplicationConstants.TOTAL_HISTORY_COUNT;
            int maxOnlineCount = ApplicationConstants.MAX_ONLINE_COUNT;
            String serverStartDate = fmt.format(ApplicationConstants.SERVER_START_DATE);
            String maxOnlineCountDate = fmt.format(ApplicationConstants.MAX_ONLINE_COUNT_DATE);
            Collection<HttpSession> list = ApplicationConstants.SESSION_MAP.values();
            List<UserInfo> userInfoList = new ArrayList<>();
            for (HttpSession s : list) {
                UserInfo userInfo = (UserInfo) s.getAttribute("userinfo");
                userInfoList.add(userInfo);
            }

            model.addAttribute("onlineCount", onlineCount);//系统在线人数
            model.addAttribute("historyCount", historyCount);//历史在线总人数
            model.addAttribute("maxOnlineCount", maxOnlineCount);//最大在线人数
            model.addAttribute("maxOnlineCountDate", maxOnlineCountDate);//最大在线发生时间
            model.addAttribute("serverStartDate", serverStartDate);//系统启动时间
            model.addAttribute("userCount", count);//管理账号数
            model.addAttribute("userInfoList", userInfoList);//在线人列表
            model.addAttribute("ip", ip);//登录ip
            return "back/main";
        } catch (Exception e) {
            logger.info("加载main页面出错 {}", e.getMessage());
        } finally {
            logger.info("加载main页面结束...");
        }

        return null;

    }


}
